import { regexp, showToast } from "utils/index";
Component({
  options: {
    styleIsolation: "apply-shared",
  },
  properties: {
    type: {
      type: String,
      value: "text",
      validator(val) {
        return [
          "text",
          "number",
          "idcard",
          "digit",
          "safe-password",
          "nickname",
          "phone",
          "captcha",
          "password",
        ].includes(val);
      },
    },
    value: {
      type: String,
      value: "",
    },
    placeholder: {
      type: String,
      value: "请输入",
    },
    clearable: {
      type: Boolean,
      value: true,
    },
  },

  data: {
    isPassword: false, //是否是密码类型
    newMaxlength: 0,
  },
  attached() {
    const maxLenMap = {
      password: 16,
      phone: 11,
      captcha: 6,
    };
    const { type } = this.data;
    this.setData({
      isPassword: type === "password",
      newMaxlength: maxLenMap[type] || 140,
    });
  },
  methods: {
    onInput(e) {
      this.triggerEvent("input", e.detail);
    },
    onClear() {
      this.setData({
        value: "",
      });
    },
    onBlur(e) {
      const { type } = this.data;
      const value = e.detail.value;
      if (type === "phone") {
        if (!value) {
          showToast("电话号码不能为空");
        } else if (!regexp.phone_11.test(value)) {
          showToast("请输入11位正确的电话号码");
        }
      } else if (type === "password") {
        if (!value) {
          showToast("密码不能为空");
        } else if (!regexp.password.test(value)) {
          showToast("请输入16位中英文混合的密码");
        }
      }
    },
  },
});
